package com.ebupt.migu.music.redis.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author liuyangyang@e-byte.com
 * @description: TODO
 * @date 2024/9/23 15:13
 */
@Component
public class RedisDistributedLock {

    private final RedisTemplate redisTemplate;

    public RedisDistributedLock(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean lock(String key, long expirationSeconds) {
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(key, "locked", expirationSeconds, TimeUnit.SECONDS);
        return locked!= null && locked;
    }

    public boolean unlock(String key) {
        return redisTemplate.delete(key);
    }
}
